package com.hjy.service;

import com.hjy.mapper.CategoryMapper;
import com.hjy.pojo.Category;
import com.hjy.vo.CategoryVo;
import com.hjy.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hjy.consts.MallConst.ROOT_PARENT_ID;

@Service
public class CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    public ResponseVo<List<CategoryVo>> selectAll(){
        List<Category> categories = categoryMapper.selectAll();
        //lambda + stream
        List<CategoryVo> categoryVoList = categories.stream()
                .filter(e -> e.getParentId()
                        .equals(ROOT_PARENT_ID))
                .map(this :: category2CategoryVo)
                .collect(Collectors.toList());

        findSubCategory(categoryVoList,categories);
        return  ResponseVo.success(categoryVoList);
    }

    private void findSubCategory(List<CategoryVo> categoryVoList,List<Category> categories){
        for (CategoryVo categoryVo : categoryVoList) {
            List<CategoryVo> subCategoryVoList = new ArrayList<>();
            for (Category category : categories) {
                //如果查到内容，设置subCategory，继续往下查
                if (categoryVo.getId().equals(category.getParentId())){
                    CategoryVo subCategoeyVo = category2CategoryVo(category);
                    subCategoryVoList.add(subCategoeyVo);
                }
                subCategoryVoList.sort(Comparator.comparing(CategoryVo::getSortOrder).reversed());
                   categoryVo.setSubCategories(subCategoryVoList);

                findSubCategory(subCategoryVoList,categories);
            }
        }
    }

    private CategoryVo category2CategoryVo(Category category){
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category,categoryVo);
        return categoryVo;
    }

    public void findSubCategoryId(Integer id, Set<Integer> resultSet) {
        List<Category> categories = categoryMapper.selectAll();
        findSubCategoryId(id, resultSet, categories);
    }

    private void findSubCategoryId(Integer id, Set<Integer> resultSet, List<Category> categories) {
        for (Category category : categories) {
            if (category.getParentId().equals(id)) {
                resultSet.add(category.getId());
                findSubCategoryId(category.getId(), resultSet, categories);
            }
        }
    }
}
